--[[
FilePath: \Lua\View\UIHeroManor\UIHeroManorCity.lua
城市界面
--]]

require 'View/UIBase/UIBase'

UIHeroManorCity = UIBase.New(PanelNames.UIHeroManorCity)
local _M = UIHeroManorCity

_M.hasInit = false
_M.cityNum = 6
_M.isClick = false
_M.unlockIndex = 0

function _M.Init()
    UIBase.Init(_M)
end

function _M:OnCreate()
    if not _M.hasInit then
        self:RegisterOnClick(self:GetChild("BackButton"), self.OnBack);
        self.title = self:GetChild("title");
        self.resBar = self:GetChild("resbar");
        self.btnHelp = self:GetChild("help");
        self.btnInfo = self:GetChild("btnInfo");
        local mapNode = self:GetChild("map");
        local mapList = mapNode:GetChildAt(0);
        mapNode.scrollPane:ScrollBottom();
        self.manorTypeCtrls = {};
        self.stateCtrls = {};
        self.iconStateCtrls = {};
        self.listHeros = {};
        self.listHeros1 = {};
        self.heroIcons = {};
        self.heroNames = {};
        self.costIcons = {};
        self.costNums = {};
        self.btnMaps = {};
        self.btnRedCtrl = {};
        for i = 1, _M.cityNum do
            local manorIcon = mapList:GetChild("ManorIcon"..i);
            table.insert(self.iconStateCtrls, manorIcon:GetController("state"));
            table.insert(self.manorTypeCtrls, manorIcon:GetController("ManorType"));
            local btn = mapList:GetChild("Manor"..i);
            table.insert(self.stateCtrls, btn:GetController("state"));
            table.insert(self.listHeros, btn:GetChild("listHero"));
            table.insert(self.listHeros1, btn:GetChild("listHero1"));
            table.insert(self.heroIcons, btn:GetChild("hero"):GetChild("icon"));
            table.insert(self.heroNames, btn:GetChild("heroManorName"));
            local redCtrl = {};
            local costNode = btn:GetChild("btnUnlock");
            redCtrl[1] = costNode:GetChild("UIRedDots"):GetController("c1");
            table.insert(self.costIcons, costNode:GetChild("cost"));
            table.insert(self.costNums, costNode:GetChild("num"));
            costNode:GetChild("title").text = getLanguage("HeroManorText01");
            local costNode2 = btn:GetChild("btnUnlock2");
            redCtrl[2] = costNode2:GetChild("UIRedDots"):GetController("c1");
            table.insert(self.btnRedCtrl, redCtrl);
            btn:GetChild("btnMoveIn").text = getLanguage("HeroManorText02");
            table.insert(self.btnMaps, btn);
        end

        self.sourceCtrl = self:GetController("showSource");
        self.btnSource = self.resBar:GetChild("add");
        self.sourceUIobj = self:GetChild("UISourceMultiple");
        self.btnJump = self.resBar:GetChild("btnJump");
        _M.hasInit = true

        self:addEvent()
    end
end

function _M:addEvent()
    self.btnHelp.onClick:Add(self.HelpTip, self);
    self.btnInfo.onClick:Add(self.OnClickInfo, self);
    self.btnSource.onClick:Add(function()
        self.sourceCtrl.selectedIndex = 1
        self:showSource();
    end);
    self.btnJump.onClick:Add(function()
        showUI(PanelNames.UIBagItemInfo, logicMgr.CostManager.getItemOrEquipDataByIdAndNum(self.costId, 0));
    end);
    self:RegisterEvent(Config.EventType.FreshManorInfo,self.RefreshManorInfo);
    self:RegisterEvent(Config.EventType.FreshManorUnlock,self.ManorUnlock);
    self:RegisterEvent(Config.EventType.Fresh_Currency,self.updateGameMoney);
    self:RegisterEvent(Config.EventType.Fresh_Bag,self.updateSource);
    for i = 1, self.cityNum do
        self.btnMaps[i].onClick:Add(function()
            _M:onClickItem(i);
        end);
    end
end

function _M:removeEvent()
    self.btnHelp.onClick:Remove(self.HelpTip);
    self.btnInfo.onClick:Remove(self.OnClickInfo);
    self.btnSource.onClick:Clear();
    self.btnJump.onClick:Clear();
    for i = 1, self.cityNum do
        self.btnMaps[i].onClick:Clear();
    end
end

function _M:HelpTip()
    logicMgr.UIShowManager.ShowCommonTips("HelpTitle1190", "HelpDes1190");
end

function _M:OnClickInfo()
    showUI(PanelNames.UIHeroManorInfo);
end

function _M:onClickItem(index)
    local state = self.stateCtrls[index].selectedIndex;
    if state == 0 then
        -- 解锁
        if self.isClick then
            return;
        end
        self.isClick = true;
        local modelData = logicMgr.HeroManorManager.getCityModelData(index);
        if modelData ~= nil then
            local costItems = decodeJsonStrToTabel(modelData.f_UnlockCost);
            local flag = true;
            for k, v in pairs(costItems) do
                local mun = logicMgr.ItemManager.getBagNumByTableID(tonumber(v[1]));
                if mun < tonumber(v[2]) then
                    local itemData = logicMgr.ItemManager.getItemConstDatabyModelId(v[1]);
                    flag = false;
                    UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),itemData.name));
                    break;
                end
            end
            if flag then
                self.unlockIndex = index;
                HeroManorHandler.sendManorUnlockMessage(1, index);
            else
                self.isClick = false;
            end
        else
            return;
        end
    elseif state == 1 then
        -- 入住
        showUI(PanelNames.UIHeroManorMoveIn, 1, index, 0);
    elseif state == 2 then
        showUI(PanelNames.UIHeroManor, 1, index);
    elseif state == 3 then
        if self.isClick then
            return;
        end
        self.isClick = true;
        self.unlockIndex = index;
        HeroManorHandler.sendManorUnlockMessage(1, index);
    elseif state == 4 then
        UISysTips.AddMsg(getLanguage("HeroManorText19"));
    end
end

-- 显示
function _M:OnEnable()
    self.costId = 1;
    local modelData = logicMgr.HeroManorManager.getCityModelData(1);
    if modelData ~= nil then
        local costItems = decodeJsonStrToTabel(modelData.f_UnlockCost);
        self.costId = costItems[1][1];
    end
    local itemData = logicMgr.ItemManager.getItemConstDatabyModelId(self.costId);
    self.resBar.icon = EnumConst.AtlasPath.ItemAtlas .. itemData.icon;
    self.btnInfo.text = getLanguage("HeroManorText03");
    self.title.text = getLanguage(dataTable.getDataTableByStringId("t_functionswitch", 1190).f_FunctionName);
    self:RefreshView();
    self:updateSource();
    self:showUnlockRed();
end

function _M:updateGameMoney()
    self:updateSource();
end

function _M:updateSource()
    self.resBar.title = getNumString(logicMgr.ItemManager.getBagNumByTableID(tonumber(self.costId)));
end

function _M:RefreshManorInfo()
    self:RefreshView();
end

function _M:RefreshView(starIndex)
    starIndex = starIndex or 1;
    for i = starIndex, self.cityNum do
        local manorInfo = logicMgr.HeroManorManager.getManorInfo(1, i);
        if manorInfo == nil then
            self.stateCtrls[i].selectedIndex = 0;
            self.iconStateCtrls[i].selectedIndex = 0;
            if i > 1 and logicMgr.HeroManorManager.getManorInfo(1, i - 1) == nil then
                self.stateCtrls[i].selectedIndex = 4;
                self.iconStateCtrls[i].selectedIndex = 4;
            else
                local modelData = logicMgr.HeroManorManager.getCityModelData(i);
                if modelData ~= nil then
                    if modelData.f_Free ~= nil and modelData.f_Free == 1 then
                        self.stateCtrls[i].selectedIndex = 3;
                        self.iconStateCtrls[i].selectedIndex = 3;
                    else
                        local costItems = decodeJsonStrToTabel(modelData.f_UnlockCost);
                        local itemData = logicMgr.ItemManager.getItemConstDatabyModelId(costItems[1][1]);
                        self.costIcons[i].icon = EnumConst.AtlasPath.ItemAtlas .. itemData.icon;
                        self.costNums[i].text = tostring(costItems[1][2]);
                    end
                end
            end
        else
            if manorInfo.masterId == nil or tonumber(manorInfo.masterId) == 0 then
                self.stateCtrls[i].selectedIndex = 1;
                self.iconStateCtrls[i].selectedIndex = 1;
            else
                self.stateCtrls[i].selectedIndex = 2;
                self.iconStateCtrls[i].selectedIndex = 2;
                self.listHeros[i]:RemoveChildrenToPool();
                self.listHeros1[i]:RemoveChildrenToPool();
                local heroInfo = logicMgr.HeroManager.getHeroDatabyPartnerId(manorInfo.masterId, true);
                if heroInfo ~= nil then
                    local heroModelId = heroInfo["partnerModelId"] or heroInfo["f_HeroID"] or 0;
                    local heroUseSkinId = logicMgr.SkinManager.getHeroSkinId(heroModelId)
                    if heroUseSkinId and tonumber(heroUseSkinId) > 0 then
                        self.heroIcons[i].url = "ui://HalfBodyAtlas/" ..logicMgr.SkinManager.GetHeroBIconBySkinId(heroUseSkinId);
                    else
                        self.heroIcons[i].url = "ui://HalfBodyAtlas/" .. heroInfo["halfIcon"];
                    end
                    self.heroNames[i].text = string.format(getLanguage("HeroManorText06"), heroInfo.name);
                    local visitors = logicMgr.HeroManorManager.getManorVisitors(manorInfo.masterId) or {};
                    for k = 1, #visitors do
                        local item
                        if k > 3 then
                            item = self.listHeros1[i]:AddItemFromPool();
                        else
                            item = self.listHeros[i]:AddItemFromPool();
                        end
                        local heroData = logicMgr.HeroManager.getHeroDatabyPartnerId(visitors[k], true);
                        if heroData ~= nil then
                            local modelId = heroData["partnerModelId"] or heroData["f_HeroID"] or 0;
                            local headIcon = item:GetChild("head"):GetChild("HeadIcon");
                            logicMgr.HeroManorManager.setHeadIcon(headIcon, modelId, heroData.icon);
                        end
                    end
                else
                    self.heroNames[i].text = "";
                end
            end
        end
    end
end

function _M:ManorUnlock()
    self.isClick = false;
    if self.unlockIndex ~= 0 then
        self:RefreshView(self.unlockIndex + 1);
        self.stateCtrls[self.unlockIndex].selectedIndex = 1;
        self.iconStateCtrls[self.unlockIndex].selectedIndex = 1;
        self.unlockIndex = 0;
    end
    self:showUnlockRed();
end

function _M:showUnlockRed()
    for i = 1, self.cityNum do
        self.btnRedCtrl[i][1].selectedIndex = 0;
        self.btnRedCtrl[i][2].selectedIndex = 0;
        local manorInfo = logicMgr.HeroManorManager.getManorInfo(1, i);
        if manorInfo == nil then
            local modelData = logicMgr.HeroManorManager.getCityModelData(i);
            if modelData ~= nil then
                if modelData.f_Free ~= nil and modelData.f_Free == 1 then
                    self.btnRedCtrl[i][2].selectedIndex = 2;
                else
                    local costItems = decodeJsonStrToTabel(modelData.f_UnlockCost);
                    local flag = true;
                    for k, v in pairs(costItems) do
                        local mun = logicMgr.ItemManager.getBagNumByTableID(tonumber(v[1]));
                        if mun < tonumber(v[2]) then
                            flag = false;
                            break;
                        end
                    end
                    if flag then
                        self.btnRedCtrl[i][1].selectedIndex = 2;
                    end
                end
            end
        end
    end
end

function _M:showSource()
    logicMgr.ItemManager.updateSourceUI(self.sourceUIobj, { self.costId }, function()
        self.sourceCtrl.selectedIndex = 0;
    end, function()
        self:OnBack();
    end);
end

-- 隐藏
function _M:OnDisable()

end

-- 卸载
function _M:OnDestroy()
    self:removeEvent();
    self.hasInit = false;
    self.isClick = false;
    self.unlockIndex = 0;
end

return _M;